<?php
// +----------------------------------------------------------------------
// | ProjectName : domall
// +----------------------------------------------------------------------
// | Description :  配置管理
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2016 http://www.idowe.com All rights reserved.
// +----------------------------------------------------------------------
// | Authors : Doogie <461960962@qq.com>  Date : 2016-03-16
// +----------------------------------------------------------------------

namespace app\admin\controller;

use think\Request;
use think\Response;

class Setting extends Base{
    private static $setting_m;
    public function __construct() {
        parent::__construct();
        self::$setting_m = model('Setting');
    }

    public function index(Request $request){
        $group = $request->param('group',0);
        if($request->isGet()){
            $group_list = self::$setting_m->getByName('config_group_list');
            $group_list = parse($group_list['type'], $group_list['value']);
            $this->assign([
                'group_list' => $group_list,
                'group' => $group
            ]);
            return $this->fetch();
        }

        $map = ['group' => $group];
        $settingList = model('Setting')->where($map)->select();
        return json([
            "rows"  =>  $settingList,
            "total" =>  count($settingList)
        ]);
    }

    /**
     * 编辑和新增
     * @param Request $request
     * @return Response|void
     */
    public function editSetting(Request $request){
        if($request->isPost()){

            if( $id = $request->post("id")){
                $state  =  model('Setting')->validate('Setting.edit')->save($request->post(),[ "id" => $id]);
            }else{
                $setting_info = $request->post();
                $state  =  model('Setting')->validate('Setting.add')->save($setting_info);
            }

            return $state ? $this->success("保存成功!") : $this->error(model('Setting')->getError());
        }else{
            $id = $request->param('id');
            $settingItem =  model('Setting')->get($id);
            $this->assign('settingItem',$settingItem);
            $this->assign([
                'meta_title' => '编辑系统配置',
                'group_list' => self::$setting_m->groups(),
                'type_list' => self::$setting_m->types()
            ]);
            return new Response($this->fetch() , 200);
        }
    }

    /**
     * 删除功能
     * @param Request $request
     */
    public function delete(Request $request){
        $id = $request->param('id');
        if( !empty($id)){
            $setting_info = model('Setting')->get($id);
            $setting_info->delete();
        }
        return $this->success('删除成功!');
    }
}